package com.bdth.bdthcms.controller;

import com.bdth.bdthcms.service.UserService;
import com.bdth.bdthcms.entity.User;
import com.bdth.bdthcms.vo.CommonResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2018-11-08
 */
@Controller
public class LoginController {

    @Value("${output.dir}")
    private String filePath;

    @Resource
    private Configuration configuration;

    @Autowired
    private UserService userService;

    @RequestMapping(value="/login", method = {RequestMethod.GET})
    public String login(){
        return "sys/login";
    }

    @RequestMapping(value="/doLogin", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult<User> doLogin(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password){
        User bean = userService.doLogin(username,password);
        if(bean!=null) {
            request.getSession().setAttribute("loginUser",bean);
            request.getSession().setMaxInactiveInterval(36000);
            return new CommonResult<User>("200", "用户登录成功", bean);
        }
        return new CommonResult<User>("400","用户名或密码错误",null);
    }

    @RequestMapping(value = "/doLogout", method = {RequestMethod.GET})
    public String doLogout(HttpServletRequest request){
        request.getSession().setAttribute("loginUser",null);
        request.getSession().removeAttribute("loginUser");
        return "redirect:/login";
    }

    @RequestMapping(value = "/chtml", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult createHtml(@RequestParam("value") String value){
        Map root = new HashMap();
        root.put("w",value);
        try{
            Template template = configuration.getTemplate("test.ftl");
            String path=filePath+"test.html";
            Writer file = new FileWriter(new File(path));
            template.process(root, file);
            file.flush();
            file.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResult.success("创建成功");
    }

}
